package com.frankle.mybatisplusgenerator.utils;

import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;

import com.frankle.mybatisplusgenerator.App;
import com.frankle.mybatisplusgenerator.constant.StageView;

import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class ViewUtils {

	public static void changeView(StageView from, StageView to) {
		Stage stage = App.STAGE_MAP.get(from);
		if(stage != null) {
			try {
				AnchorPane pane = FXMLLoader.load(App.class.getResource(to.getViewPath()));
				Scene scene = new Scene(pane, pane.getPrefWidth(), pane.getPrefHeight());
				stage.setScene(scene);
				if(!"".contentEquals(to.getTitle())) {
					stage.setTitle(to.getTitle());
				}
				stage.centerOnScreen();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 显示窗口
	 * @author Frankle
	 * @date 2020年5月20日
	 * @param optionsView
	 */
	public static Stage showView(StageView optionsView, boolean resizable, boolean modal) {
		Stage stage = App.STAGE_MAP.get(optionsView);
		if(stage == null) {
			stage = new Stage();
			Pane pane = loadView(optionsView);
			Scene root = new Scene(pane, pane.getPrefWidth(), pane.getPrefHeight());
			stage.setScene(root);
			stage.titleProperty().bind(I18N.createStringBinding(optionsView.getTitle()));
			stage.setResizable(resizable);
			if(modal) {
				stage.initModality(Modality.APPLICATION_MODAL);
			}
			App.STAGE_MAP.put(optionsView, stage);
			stage.showAndWait();
		} else {
			stage.showAndWait();
		}
		return stage;
	}
	
	/**
	 * 加载视图
	 * @author Frankle
	 * @date 2020年5月20日
	 * @return
	 */
	public static Pane loadView(StageView view) {
		Locale locale = Locale.getDefault();
		
		ResourceBundle bundle = ResourceBundle.getBundle("language.messages", locale);
		Pane pane = null;
		try {
			pane = FXMLLoader.load(ViewUtils.class.getResource(view.getViewPath()), bundle);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return pane;
	}
}
